package com.liurong.quartz.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.liurong.util.redis.RedisTemplate;

/**
 * 选举主应用线程并且发送心跳
 * 
 * @author liurong
 *
 */
public class MasterThread extends Thread {
	private static final Logger logger = LoggerFactory.getLogger(MasterThread.class);
	private RedisTemplate redisTemplate;
	private ClusterThread clusterThread;
	private String localIpStr;

	public MasterThread(ClusterThread clusterThread, RedisTemplate redisTemplate, String localIpStr) {
		this.clusterThread = clusterThread;
		this.redisTemplate = redisTemplate;
		this.localIpStr = localIpStr;
	}

	@Override
	public void run() {
		String heartbeatValue = null;
		// 循环发送心跳
		while (!JobStartConfig.isStop) {
			try {
				Thread.sleep(1000 * 30);
				heartbeatValue = redisTemplate.get("jedis_lock_" + ClusterThread.JOB_HEART_BEAT_REDIS_KEY);
				if (!localIpStr.equals(heartbeatValue)) {
					logger.error("不是自己的心跳，退出主机模式！");
					clusterThread.setMain(false);
					return;
				}
				redisTemplate.lock(ClusterThread.JOB_HEART_BEAT_REDIS_KEY, localIpStr, 1000 * 30, 0);
			} catch (Exception e) {// 防御性容错
				logger.error("MasterThread error:", e);
			}
		}
	}
}
